
/**
 * Module dependencies.
 */

var express = require('express');
var i18n    = require("i18n");
var routes  = require('./routes');
var logcfg = require('./config.js');
var http = require('http');
var path = require('path');
var uuid = require('node-uuid');
var fs = require('fs');
var partials = require('express-partials');
var helpers = require('express-helpers');
var fhelper = require('form-converter');
var images = require("images");
var app = express();
var MongoStore = require('connect-mongo')(express);
var secContext = require('local-security')();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');


app.use(express.favicon());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.bodyParser({uploadDir:'public/images'}));
//app.use(express.cookieSession({key:'west2.sess',secret :"west2"}));
app.use(express.session({
    secret: "west2",
    key: 'west2.sess',
    cookie: {maxAge: 10*60*1000},
    store: new MongoStore({
        db: "west2"
    })
}));
app.use(partials());
helpers(app);
fhelper(app);
// development only
if ('development' == app.get('env')) {
    app.use(express.errorHandler());
}
logcfg.logInit(app);
var logger = logcfg.logger('west2');
app.use(secContext.authentication());

i18n.configure({
    locales:['zh', 'en'],
    directory: __dirname + '/public/locales',
    defaultLocale: 'zh',
    cookie: 'wlocal',
    updateFiles: false,
    indent: "\t",
    // setting extension of json files - defaults to '.json' (you might want to set this to '.js' according to webtranslateit)
    extension: '.json'
});
// default: using 'accept-language' header to guess language settings
app.use(i18n.init);
app.get('/login', routes.login);
app.get('/logout', routes.logout);
app.post('/signin',secContext.authorize);


app.use(app.router);

/**延迟注册控制器**/
var modules= [
    'worklog',
    'users',
    'article',
    'articlec',
    'vmessage',
    'friends',
    'groups',
    'webrest',
    'company',
    'child',
    'webobject'

];
for(var m in modules){
    var mk= modules[m];
    require('./routes/'+mk)(app,i18n);
}


/**控制器注册完成**/
app.get('/admin',routes.admin);

app.post('/images/upload', function(req, res) {

    logger.info(req.files.upload.type);
    var num = req.query.CKEditorFuncNum;
    var ppath = req.files.upload.path;
    var fpath = path.resolve(__dirname,ppath);

    var ext = path.extname(ppath).toLowerCase();
    logger.info(ext);
    var isimg = ext=='.jpg'||ext=='.png'||ext=='.gif';
    if(req.session.loginUser==null || !isimg){

        fs.unlink(fpath);
        var result={'path':'error'};
        res.send(JSON.stringify(result));
        return;

    }

    var tname = uuid.v1();
    var flag = path.resolve(__dirname,"public/images/flag.png");
    var temp = path.resolve(__dirname,"public/images/"+tname+ext);
    try {
        images(fpath)

            .draw(images(flag), 0, 0)
            .save(temp, {
                quality: 60
            });

        fs.rename(temp, fpath, function(err) {
            if (err) {
                logger.error(err.message);
            }
            fs.unlink(temp, function(errs) {
                if (errs) logger.error(errs);
            });
        });

    }catch(e){
        logger.info(e.message);
        fs.unlink(fpath, function(errs) {
            if (errs) logger.error(errs);
        });
        var result={'path':'file size exceed the limit of 213654'};
        res.send(JSON.stringify(result));
        return;
    }
    ppath = ppath.replace('public','');
    ppath = ppath.replace(/\\/g,'/');

    res.send("<script>window.parent.CKEDITOR.tools.callFunction("
        + num +
        ",'" +ppath+ "'"+",'');</script>");
});

app.post('/images/json', function(req, res) {


    var ppath = req.files.files.path;
    console.log("上传类型: "+req.files.files.type);

    var fpath = path.resolve(__dirname,ppath);
    ppath = ppath.replace('public','');
    ppath = ppath.replace(/\\/g,'/');

    console.log("上传路径  : "+ppath);

    var result = {'path':ppath};
    var ext = path.extname(ppath).toLowerCase();
    var isimg = ext=='.jpg'||ext=='.png'||ext=='.gif';
    if(req.session.loginUser==null|| !isimg){

        fs.unlink(fpath);
        var result={'path':'/images/errors.png'};
        res.send(JSON.stringify(result));
        return;
    }

    var tname = uuid.v1();
    var flag = path.resolve(__dirname,"public/images/flag.png");
    var temp = path.resolve(__dirname,"public/images/"+tname+ext);
    try {
        images(fpath)

            .draw(images(flag), 0, 0)
            .save(temp, {
                quality: 60
            });

        fs.rename(temp, fpath, function(err) {
            if (err) {
                logger.error(err.message);
            }
            fs.unlink(temp, function(errs) {
                if (errs) logger.error(errs);
            });
        });

    }catch(e){
        logger.info(e.message);
        fs.unlink(fpath, function(errs) {
            if (errs) logger.error(errs);
        });
        var result={'path':'/images/errors.png'};
        res.send(JSON.stringify(result));
        return;
    }



    res.send(JSON.stringify(result));
});

exports.startServer = function(port){
    http.createServer(app).listen(port, function(){
          logger.info('Express server listening on port ' +  port);
    });
}